package com.amumu.drama.common.commpont.notify;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.constant.NotifyTemplateKeyEnum;
import com.amumu.drama.common.utils.date.DatetimeUtils;
import com.amumu.drama.model.OmsOrder;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author sunzhuang
 * @date 2024/10/25 10:08
 * @slogan 天下风云出我辈, 一入代码岁月催
 * @desc todo
 */
@Slf4j
public class OrderNotifyUtils {

    public static String getTemplate(NotifyTemplateKeyEnum keyEnum) {
        return NotifyConfigLoader.NOTIFY_TEMPLATE.getOrDefault(keyEnum.getTemplateKey(), NotifyConfigLoader.NOTIFY_TEMPLATE.get(keyEnum.getKey()));
    }

    public static void manualOrderNotify(OmsOrder order) {
        Map<String, String> params = Maps.newHashMap();
        commonOrder(order, params);
        businessNotify(NotifyTemplateKeyEnum.MANUAL_ORDER_NOTIFY, params);
    }

    public static void manualOrderDelayNotify(OmsOrder order) {
        Map<String, String> params = Maps.newHashMap();
        commonOrder(order, params);
        businessNotify(NotifyTemplateKeyEnum.MANUAL_ORDER_DELAY_NOTIFY, params);
    }

    public static void commonOrder(OmsOrder order, Map<String, String> params) {
        params.put("feature", NotifyUtils.escapeMessage(JSONUtil.toJsonPrettyStr(order.getFeature())));
        params.put("orderId", order.getId() + "");
        params.put("memberId", order.getMemberId() + "");
        Long diffMinute = DatetimeUtils.between(LocalDateTime.now(), order.getCreateTime(), DateUnit.MINUTE);
        long days = diffMinute / (60 * 24);
        long leftMinute = diffMinute % (60 * 24);
        params.put("diffCreateTime", days + "天" + (leftMinute / 60) + "时" + (leftMinute % 60) + "分");
        params.put("totalAmount", order.getTotalAmount().toString());
    }

    /**
     * 推送报警消息
     * 此方法本应由Log.error自动触发，不推荐手动调用
     */
    public static void businessNotify(NotifyTemplateKeyEnum keyEnum, Map<String, String> params) {
        if (CollUtil.isEmpty(params) || keyEnum == null) {
            return;
        }

        if (NotifyConfigLoader.NOTIFY_CONFIG.getEnable() == 0) {
            return;
        }
        String template = getTemplate(keyEnum);
        if (StrUtil.isBlank(template)) {
            log.error("未配置报警模板，请先配置，key:{}", keyEnum);
            return;
        }
        params.put("defaultTitle", keyEnum.getDesc());
        String msg = StrUtil.format(template, params);

        String[] ignoreIfMatchStart = NotifyConfigLoader.NOTIFY_CONFIG.getErrorIgnoreIfMatchStart();
        if (ignoreIfMatchStart != null && ignoreIfMatchStart.length > 0) {
            if (StringUtils.startsWithAny(msg, ignoreIfMatchStart)) {
                return;
            }
        }

        String[] ignoreIfMatchEnd = NotifyConfigLoader.NOTIFY_CONFIG.getErrorIgnoreIfMatchEnd();
        if (ignoreIfMatchEnd != null && ignoreIfMatchEnd.length > 0) {
            if (StringUtils.endsWithAny(msg, ignoreIfMatchEnd)) {
                return;
            }
        }
        pushToQueue(msg);
    }


    private static void pushToQueue(String content) {
        try {
            Notifier.Holder.INSTANT.addMessage(content);
        } catch (Throwable e) {
            Notifier.Holder.INSTANT.addMessage("NotifyUtils.notify error");
        }
    }


}